package org.microblog.service.impl;


import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.microblog.dao.CollectionDao;
import org.microblog.dao.CommentDao;
import org.microblog.dao.LikesDao;
import org.microblog.entity.Blog;
import org.microblog.entity.Comment;
import org.microblog.entity.CommentVo;
import org.microblog.service.CommentService;

import org.microblog.util.Page;
import org.microblog.util.SessionFatoryUtil;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CommentServiceImpl implements CommentService {
    SqlSessionFactory sessionFactory = SessionFatoryUtil.sessionFactory;
    CommentVo vo=new CommentVo();
    @Override
    public int getCommentCountByBid(int bid) throws SQLException {
        SqlSession sqlSession=sessionFactory.openSession();
        CommentDao dao=sqlSession.getMapper(CommentDao.class);
        int ret=dao.getCommentCountByBid(bid);
        sqlSession.commit();
        sqlSession.close();
        return ret;
    }

    @Override
    public List<Comment> getCommentsByBid(int bid) throws SQLException {
        SqlSession sqlSession=sessionFactory.openSession(true);
        CommentDao dao=sqlSession.getMapper(CommentDao.class);
        sqlSession.commit();
        sqlSession.close();
        List<Comment> list=dao.getCommentsByBid(bid);
        return list;
    }

    @Override
    public int addComment(Comment comment) throws SQLException {
        SqlSession sqlSession=sessionFactory.openSession();
        CommentDao dao=sqlSession.getMapper(CommentDao.class);
        int ret=dao.addComment(comment);
        sqlSession.commit();
        sqlSession.close();
        return ret;
    }

    @Override
    public int deleteCommentsByBid(int bid) throws SQLException {
        SqlSession sqlSession=sessionFactory.openSession();
        CommentDao dao=sqlSession.getMapper(CommentDao.class);
        int ret=dao.deleteCommentsByBid(bid);
        sqlSession.commit();
        sqlSession.close();
        return ret;
    }

    @Override
    public void getCommentsByPage(int bid, Page pageObj) throws SQLException {
        SqlSession sqlSession=sessionFactory.openSession(true);
        vo.setBid(bid);
        vo.setPageNo(pageObj.getBeginIndex());
        vo.setPageSize(pageObj.getPageSize());
        CommentDao commentDao = sqlSession.getMapper(CommentDao.class);
        int totalCount = commentDao.getCommentCountByBid(bid);
        if (totalCount > 0) {
            if (pageObj.getCurrPageNo() > pageObj.getTotalPageCount())
                pageObj.setCurrPageNo(pageObj.getTotalPageCount());
            List<Comment> commentList = commentDao.getCommentsByPage(vo);
            pageObj.setCommentList(commentList);
        } else {
            pageObj.setCurrPageNo(0);
            pageObj.setBlogsList(new ArrayList<>());
        }
        sqlSession.commit();
        sqlSession.close();
    }
}
